package de.gameduell.framework.gui.animation {
	import fl.transitions.TweenEvent;
	
	import de.gameduell.framework.debug.Debug;
	import de.gameduell.framework.gui.animation.Tweenable;
	
	import flash.events.EventDispatcher;	

	/**
	 * @author cbra
	 */
	public class CombinedTween extends EventDispatcher implements Tweenable {

		protected var _tweenList:Array;
		protected var _tweenCounter:int;
		protected var _isPlaying:Boolean;

		public function CombinedTween(aTweenList:Array = null) {
			_tweenList = aTweenList == null ? new Array() : aTweenList;
			_tweenCounter = aTweenList == null ? 0 : aTweenList.length;
			TweenManager.getInstance().add(this);
		}

		/**
		 * adds a tween to the tween list
		 */
		public function addTween(tween:Tweenable):void {
			_tweenCounter++;
			_tweenList.push(tween);		
		}

		public function clear():void {
			_tweenList = new Array();
		}

		/**
		 * starts all tweens in the tween list
		 */
		public function start():void {
			_tweenCounter = _tweenList.length;
			if (_tweenCounter == 0) {
				dispatchEvent(new TweenEvent(TweenEvent.MOTION_FINISH, 0, 0));
				Debug.trace("CombinedTween::start: cannot start tweening without tweens! ", Debug.ERROR);
			} else {
				_isPlaying = true;
				for (var i:int = 0;i < _tweenList.length;i++) {
					var tween:Tweenable = _tweenList[i];
					tween.addEventListener(TweenEvent.MOTION_FINISH, onMotionEvent);
					tween.start();
				}
			}
		}
		
		public function get tweenList():Array{
			return _tweenList;
		}
		
		public function get tweenCount():int{
			return _tweenCounter;
		}

		/**
		 * stops all tweens in the tween list
		 */
		public function stop():void {
			_isPlaying = false;
			for (var i:int = 0;i < _tweenList.length;i++) {
				var tween:Tweenable = _tweenList[i];
				tween.stop();
			}
		}

		protected function onMotionEvent(event:TweenEvent):void {
			if(event.type == TweenEvent.MOTION_FINISH) {
				_tweenCounter--;
			}
			if(_tweenCounter == 0) {
				_isPlaying = false;
				dispatchEvent(new TweenEvent(TweenEvent.MOTION_FINISH, event.time, event.position, event.bubbles, event.cancelable));
			}
		}

		public function get isPlaying():Boolean {
			return _isPlaying;
		}
	}
}
